(function () {
    "use strict";
    angular.module('userSettings', ['accountManage', 'commons'])
        .factory('LoginInfo', function ($http, urlPrefix) {
            var loginInfo = {}, begin = Date.now();
            return $http.get(urlPrefix + '/loginInfo.do?time='+begin).then(function (resp) {
                loginInfo.currentUser = resp.data.currentUser;
                loginInfo.sessionsSize = resp.data.sessionsSize;
                var serverTime = resp.headers('Date');
                loginInfo.severTimeDelay = serverTime ? new Date(serverTime) - begin : 0;
                return loginInfo;
            });
        })
        .directive('userBar', function (LoginInfo, $timeout, Promise, $rootScope, tabService, urlPrefix, loadConf) {
            return {
                restrict: 'A',
                scope: {},
                link: function (scope) {
                    scope.hasChangeUserRole = false;
                    Promise.when(LoginInfo).then(function (loginInfo) {
                        scope.currentUser = loginInfo.currentUser;
                        scope.sessionsSize = loginInfo.sessionsSize;
                        (function now() {
                            scope.now = loginInfo.severTimeDelay + Date.now();
                            $timeout(now, 1000);
                        }());
                        loadConf('commons-settings.yml').then(function (setting) {
                            var changeUserRoleId = setting.changeUserRoleId;
                            angular.forEach(loginInfo.currentUser.roles, function (n) {
                                if (n.ROLE_ID == changeUserRoleId) {
                                    scope.hasChangeUserRole = true;
                                }
                            })
                        });
                        scope.showAccountManagePanel = function () {
                            $rootScope.$emit('showAccountManageCenter');
                        };
                        scope.changeLoginUser = function (tabName) {
                            tabService.addTab({
                                name: tabName,
                                url: urlPrefix + "/loadUserManage.do?type=changeLoginUser"
                            });
                        };
                        scope.showNoticeCenterPanel = function (status) {
                            $rootScope.$emit('showNoticeCenter', status);
                        }
                    });
                },
                replace: true,
                templateUrl: 'app/user/user-bar.html'
            };
        });
}());